<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="close">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="权限名称" prop="name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code" :label-width="formLabelWidth">
        <el-input v-model="form.code" autocomplete="off" />
      </el-form-item>
      <el-form-item label="权限描述" :label-width="formLabelWidth">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
      <el-form-item label="开启" :label-width="formLabelWidth">
        <el-switch
          v-model="form.enVisible"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogShow = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addPermissionAPI, permDetailAPI, updatePermAPI } from '@/api/permission'
export default {
  props: {
    pid: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      title: '添加权限',
      dialogShow: false,
      formLabelWidth: '80px',
      form: {
        name: '',
        code: '',
        description: '',
        enVisible: '1'
      },
      rules: {
        name: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 点击保存的方法
    async save() {
      try {
        await this.$refs.form.validate()
        if (this.title === '添加权限') {
        // 通过了发请求做新增
          await addPermissionAPI({
            ...this.form,
            pid: this.pid,
            type: this.pid === '0' ? 1 : 2
          })
          this.$message.success('添加权限成功')
        } else {
          // 修改
          await updatePermAPI(this.form)
          this.$message.success('更新权限成功')
        }
        this.dialogShow = false
        this.$emit('reload')
      } catch {
        console.log('不通过')
      }
    },
    // 关闭对话框调用--做清除
    close() {
      this.form = {
        name: '',
        code: '',
        description: '',
        enVisible: '1'
      }
      this.$refs.form.clearValidate()
    },

    async show(id) {
      if (id) {
      // 根据id发请求获取详情
        const res = await permDetailAPI(id)
        this.form = res.data
        // 改变标题
        this.title = '编辑权限'
      } else {
        this.title = '添加权限'
      }
      this.dialogShow = true
    }
  }
}
</script>

<style>

</style>
